package cn.topcodes.tcsf.admin.web.security;

import cn.topcode.unicorn.utils.ByteUtil;
import cn.topcodes.tcsf.admin.commons.api.security.ShiroUser;
import cn.topcodes.tcsf.admin.service.security.SecurityService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import cn.topcodes.tcsf.admin.domain.entity.SysUser;
import cn.topcodes.tcsf.admin.service.org.SysUserService;

import javax.annotation.PostConstruct;
import java.util.List;

public class AdminRealm extends AuthorizingRealm {
	
	@Autowired
	private SysUserService userService;
	
	@Autowired
	private SecurityService securityService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		List<String> roleCodes = this.securityService.getRoleCodeByUserId(shiroUser.getUserId());
		List<String> permCodes = this.securityService.getPermCodeByUserId(shiroUser.getUserId());
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRoles(roleCodes);
		info.addStringPermissions(permCodes);
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		String username = usernamePasswordToken.getUsername();
		SysUser user = this.userService.findByUsername(username);
		if(user != null) {
			byte[] salt = ByteUtil.hex2byte(user.getSalt());
			ShiroUser shiroUser = new ShiroUser(user.getId(),user.getUsername(),user.getRealName());
			return new SimpleAuthenticationInfo(shiroUser, user.getPassword(), ByteSource.Util.bytes(salt), getName());
		}
		return null;
	}

	/**
	 * 设定Password校验的Hash算法与迭代次数.
	 */
	@PostConstruct
	public void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(SysUserService.HASH_ALGORITHM);
		matcher.setHashIterations(SysUserService.HASH_INTERATIONS);
		setCredentialsMatcher(matcher);
	}
	
}
